<?php

function invalid_expression($expression)
{
	if (preg_match('/\/[ ]*0[.0]?[0]*/i', $expression) > 0)
		return 'Divide by Zero';
	else if (preg_match('/^[\s]*[\-]?[0-9]+[\s]*([\+\-\*\/][\s]*[\-]?[0-9]+)*[\s]*$/', $expression) > 0)
		return false;
	else if (preg_match('/^[\-]?[0-9]+[\s]*([\+\-\*\/][\s]*[\-]?[0-9]+)*$/', $expression) > 0)
		return false;
	else if (preg_match('/[A-Z]+[a-z]+/i', $expression) > 0)
		return 'Alphabetical Characters not allowed';
	else
		return 'Invalid';
}

function evaluate_expression($expression)
{
	eval('$answer = '.$expression.';');
	return $answer;
}

if (isset($_POST['submit']))
{
	$expression = $_POST['expression'];
	$error = invalid_expression($expression);
	if ($error === false)
		$answer = evaluate_expression($expression);
}
?>
<!DOCTYPE html>
<html>
	<head>
		<title>CS143 Project 1A: PHP Calculator</title>
	</head>
	<body>
		<h1>PHP Calculator</h1>
		<div id="form">
			<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
				<label for="expression">Enter Expression to be Evaluated</label>
				<input type="text" name="expression" id="expression">
				<input type="submit" value="Calculate" name="submit" id="submit">
			</form>
		</div>
		<?php if (isset($answer) && $answer) { ?>
		<div id="answer">
			<p>The answer is: <?php echo $answer; ?></p>
		</div>
		<?php } ?>
		<?php if ($error) { ?>
		<div id="error">
			<p>Syntax error detected: <?php echo $error; ?>!</p>
		</div>
		<?php } ?>
	</body>
</html>